package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    //自动注入自定义的文件存储服务
    private FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;
    /**
     * 上传图片接口
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (multipartFile==null||multipartFile.getSize()==0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上传文件不能为空");
        }
        //获取当前线程中的userId
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"未查询到用户信息，请登陆后重试");
        }
        //获取上传的文件的名子
        String originName = multipartFile.getOriginalFilename();
        String suffix = originName.substring(originName.lastIndexOf("."));
        if(!checkFileSuffix(suffix)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上传的文件不符合要求 【jap，png，jpeg，gif】");
        }
        //将文件上传到oss中
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件oss中的地址
        try {
            String store = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());
            //素材表添加一条元素
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(store);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
            return ResponseResult.okResult();
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败，服务器出现异常");
        }
        return null;
    }

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //参数校验
        dto.checkParam();
        //执行业务查询
        Page<WmMaterial> reqPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //搜藏条件
        if (dto.getIsCollection()==1) {
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //当前登陆用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"未查询到当前用户信息，请重新登陆");
        }
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //根据时间倒叙排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageResult = this.page(reqPage, wrapper);
        //遍历对象结果，从新设置url
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        //封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(),records);
        return pageResponseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 删除图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 参数校验
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"id参数不能为空");
        }
        //判断当前id是否在数据库中存在
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前数据不存在，请刷新后重试");
        }
        //判断当前id是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getMaterialId, id));
        if (count>0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前数据正在被引用，无法操作数据！！！");
        }
        //删除素材库
        removeById(id);
        //删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        //封装返回数据结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //参数校验
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"本条数据信息已经不存在，请刷新后重试");
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"本条数据信息已经不存在，请刷新后重试");
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //判断当前用户操作的是否是自己的数据
        if (!wmMaterial.getUserId().equals(uid)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户只允许收藏自己上传的素材");
        }
        wmMaterial.setIsCollection(type);
        this.updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    /**
     *  检查文件名字后缀是否复合要求
     */
    private boolean checkFileSuffix(String suffix) {
        List<String> list = Arrays.asList(".jpg", ".png", ".jped", ",gif");
        for (String allowSuffix : list) {
            if (suffix.equals(allowSuffix)) {
                return true;
            }
        }
        return false;
    }


}
